/* 
 *  轮播图子类
 *  开发：Amron
 *  日期：6-18
 */

import BaseSlider from './baseSlider';
import { CURRENT_CIRCLE_CLASSNAME } from './constants';

class ButtonSlider extends BaseSlider {

  constructor(el, options, btn, circles) {
    super(el, options);

    // 获取按钮和小圆点的元素节点
    this.btn = btn;
    this.circles = circles;

    // 自动播放的定时器
    this.timer = '';
    // 节流锁的标志
    this.lock = false;

    this.bindEvents();
    this.initSet();
  }

  initSet() {
    // 小圆点初始化
    this.circleInit();
    // 开启自动
    if (this.options.autoPlay) this.setAuto();
  }

  // 绑定左右按钮和小圆点的点击事件
  bindEvents() {
    const [leftBtn, rightBtn] = this.btn.children;

    leftBtn.addEventListener('click', () => {
      // 节流锁
      if (this.lock) return;
      this.setLock();

      // 显示上一张，同时改变小圆点样式
      this.prev();
      this.circlesChange();
    });

    rightBtn.addEventListener('click', () => {
      // 节流锁
      if (this.lock) return;
      this.setLock();

      // 显示下一张，同时改变小圆点样式
      this.next();
      this.circlesChange();
    });

    // 通过事件委托实现小圆点的点击事件监听
    this.circles.addEventListener('click', e => {
      if (e.target.tagName.toLowerCase() === 'li') {
        this.to(e.target.dataset.n);
        this.circlesChange();
      }
    });
  }

  // 轮播图自动定时器
  setAuto() {
    this.timer = setInterval(() => {
      this.next();
      this.circlesChange();
    }, 2000);
  }

  // 小圆点样式变化
  circlesChange() {
    // 获取所有小圆点元素
    const circle = this.circles.children;
    // 遍历小圆点，进行样式修改
    for (const item of circle) {
      if (item.dataset.n == this.currIndex) item.classList.add(CURRENT_CIRCLE_CLASSNAME);
      else item.classList.remove(CURRENT_CIRCLE_CLASSNAME);
    }
  }

  // 小圆点初始化
  circleInit() {
    this.circles.children[this.currIndex].classList.add(CURRENT_CIRCLE_CLASSNAME);
    const width = 20 * this.number + 10 * this.maxIndex + 20;
    this.circles.style.width = `${width}px`;
    this.circles.style.marginLeft = `-${width / 2}px`;
  }


  // 节流锁
  setLock() {
    this.lock = true;
    setTimeout(() => {
      this.lock = false;
    }, this.options.speed)
  }
}

export default ButtonSlider;